using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using FU.Capstones.IMS.Web.Common;
using FU.Capstones.IMS.Web.Common.InventoryServiceProxy.DataContracts;
using FU.Capstones.IMS.Web.Common.InventoryServiceProxy.EventArgs;
using FU.Capstones.IMS.Web.Silverlight.Models;
using Microsoft.Practices.Prism.Commands;
using Navigation.Silverlight;

namespace FU.Capstones.IMS.Web.Silverlight.ViewModels
{
    public class MaterialDetailViewModel : ViewModelBase
    {
        public MaterialDetailViewModel()
        {
            Model = new MaterialDetailModel();
            ((MaterialDetailModel)Model).GetSingleMaterialCompleted += DoGetSingleMaterialCompleted;
            ((MaterialDetailModel)Model).InsertMaterialCompleted += DoInsertMaterialCompleted;
            ((MaterialDetailModel)Model).UpdateMaterialCompleted += DoUpdateMaterialCompleted;

            IsFirstLoaded = false;
            ErrorMessageVisibility = Visibility.Collapsed;
            MessageVisibility = Visibility.Collapsed;

            CanEditOrAdd = CurrentUser.CanEditMaterial || CurrentUser.CanAddMaterial;
            CanAdd = CurrentUser.CanAddMaterial;
        }

        #region Do Completed Methods

        void DoUpdateMaterialCompleted(object sender, FeedbackCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                Message = e.Error.Message;
                SetMessageVisibility(false);
            }
            else
            {
                Message = e.Result.Message;
                SetMessageVisibility(e.Result.IsSuccessful);

                if (e.Result.IsSuccessful)
                {
                    Backup();
                }
            }
            ServiceCallCounter -= WebConstants.MagicNumer;
        }

        void DoInsertMaterialCompleted(object sender, SingleFeedbackCompletedEventArgs<int> e)
        {
            if (e.Error != null)
            {
                Message = e.Error.Message;
                SetMessageVisibility(false);
            }
            else
            {
                Message = e.Result.Message;
                SetMessageVisibility(e.Result.IsSuccessful);
                if (e.Result.IsSuccessful)
                {
                    isCreateNew = false;
                    Material.MaterialID = e.Result.Data;
                    Backup();
                }
            }
            ServiceCallCounter -= WebConstants.MagicNumer;
        }

        void DoGetSingleMaterialCompleted(object sender, SingleFeedbackCompletedEventArgs<Material> e)
        {
            if (e.Error != null)
            {
                Message = e.Error.Message;
                SetMessageVisibility(false);
            }
            else
            {
                Message = e.Result.Message;
                SetMessageVisibility(e.Result.IsSuccessful);
                if (e.Result.IsSuccessful)
                {
                    Material = new Material()
                    {
                        MaterialCode = e.Result.Data.MaterialCode,
                        Description = e.Result.Data.Description,
                        MaterialID = e.Result.Data.MaterialID,
                        MaterialName = e.Result.Data.MaterialName
                    };
                    Backup();
                }
            }
            ServiceCallCounter -= WebConstants.MagicNumer;
        }

        #endregion

        #region Commands

        #region SaveCommand

        private DelegateCommand<object> saveCommand;
        public DelegateCommand<object> SaveCommand
        {
            get
            {
                if (saveCommand == null)
                    saveCommand = new DelegateCommand<object>(DoSaveCommand);
                return saveCommand;
            }
        }

        private void DoSaveCommand(object obj)
        {
            Material.ValidateAll();
            if (!Material.HasErrors)
            {
                if (isCreateNew)
                {
                    ServiceCallCounter += ((MaterialDetailModel)Model).InsertMaterialAsync(Material);
                }
                else
                {
                    ServiceCallCounter += ((MaterialDetailModel)Model).UpdateMaterialAsync(Material);
                }
            }
            else
            {
                Message = WebConstants.InvalidInputDataMessage;
                SetMessageVisibility(false);
            }
        }

        #endregion

        #region CancelCommand

        private DelegateCommand<object> cancelCommand;
        public DelegateCommand<object> CancelCommand
        {
            get
            {
                if (cancelCommand == null)
                    cancelCommand = new DelegateCommand<object>(DoCancelCommand);
                return cancelCommand;
            }
        }

        private void DoCancelCommand(object obj)
        {
            NavigationManager.NavigateTo(WebConstants.NavigationPages.MaterialList);
        }

        #endregion

        #region ResetCommand

        private DelegateCommand<object> resetCommand;
        public DelegateCommand<object> ResetCommand
        {
            get
            {
                if (resetCommand == null)
                    resetCommand = new DelegateCommand<object>(DoResetCommand);
                return resetCommand;
            }
        }

        private void DoResetCommand(object obj)
        {
            if (isCreateNew)
                Material = new Material();
            else
            {
                Material = partnerTemp;
                Backup();
            }
        }

        #endregion

        #endregion

        #region Binding Properties

        private Material partner;
        public Material Material
        {
            get { return partner; }
            set
            {
                if (!ReferenceEquals(partner, value))
                {
                    partner = value;
                    RaisePropertyChanged(() => Material);
                }
            }
        }

        private ObservableCollection<Material> materialCollection;
        public ObservableCollection<Material> MaterialCollection
        {
            get { return materialCollection; }
            set
            {
                if (!ReferenceEquals(materialCollection, value))
                {
                    materialCollection = value;
                    RaisePropertyChanged(() => MaterialCollection);
                }
            }
        }

        #endregion

        #region Fields

        private bool isCreateNew;
        private Material partnerTemp;

        #endregion

        #region Implementation of INavigationAware

        public override void OnNavigate(object extraData)
        {
            int? partnerID = (int?)extraData;
            isCreateNew = (partnerID.HasValue == false || partnerID.Value == 0);
            if (!isCreateNew)
            {
                ServiceCallCounter += ((MaterialDetailModel)Model).GetSingleMaterialAsync(partnerID.Value);
            }
            else
            {
                Material = new Material();
            }
            Message = "Đang kết nối tới máy chủ...";
        }

        public override void OnLeave()
        {
            //throw new NotImplementedException();
        }

        #endregion

        private void Backup()
        {
            if (Material != null)
            {
                partnerTemp = new Material()
                {
                    MaterialCode = partner.MaterialCode,
                    Description = partner.Description,
                    MaterialID = partner.MaterialID,
                    MaterialName = partner.MaterialName
                };
            }
        }
    }
}